package com.tuling.code.ratelimit;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
	static Semaphore semaphore = new Semaphore(10);
	
	public static void main(String[] args) {
		ExecutorService excService = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 100; i++) {
			/*excService.submit(new Runnable() {
				@Override
				public void run() {
					handle();
				}
			});*/
			excService.submit(()-> handle());
		}
	}

	private static void handle() {
		boolean acquire = acquire();
		try {
			if(acquire){
				System.out.println("业务执行中...");
			}else {
				System.out.println("**************我被拒绝了**************");
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			release(); //释放资源
		}
	}
	
	public static boolean acquire(){
		return semaphore.tryAcquire();
	}
	
	public static void release(){
		semaphore.release();
	}
}
